package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.LockRecordAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.LockRecord;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Lock;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RemoteLockActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	// private TextView mTitleTv;
	private ListView mRecordL;
	private ImageView mLockb;
	private Button mRegisterB;
	private Button mCancelB;
	private int p;
	private Device device;
	private MySocket socket;
	// private int[] getData = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8,
	// 34,
	// 0, 0, 0, 0, 0, 1, 0 };
	// private int[] getData1 = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8,
	// 35,
	// 0, 0, 0, 0, 0, 1, 0 };
	// private int[] getData2 = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8,
	// 36,
	// 0, 0, 0, 0, 0, 1, 0 };
	private String mac;
	private String registerCmd;
	private String cancelCmd;
	private String openCmd;
	private int[] macInt = { 256, 256, 256, 256 }; // 定义一个数组 256是因为16进制转换不会出现256
	// 可以规避重复
	private int[] macRecInt = { 257, 257, 257, 257, 257 };// 定义从网关返回的指令解析出来的mac地址
	private LockRecordAdapter mAdapter;
	private List<LockRecord> records = new ArrayList<LockRecord>();
	// 257是规避与macInt数组重复
	private int page = 1;
	private SVProgressHUD mSvProgressBar;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.lock_img:
			// 开锁
			mSvProgressBar.showWithStatus("正在开锁");
			checkTimeout();
			socket.sendMqttData(openCmd);
			break;
		case R.id.register_btn:
			// 注册
			socket.sendMqttData(registerCmd);
			break;
		case R.id.cancel_btn:
			// 注销
			socket.sendMqttData(cancelCmd);
			break;
		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if(mSvProgressBar.isShowing()){
					mSvProgressBar.dismiss();
				}
				ToastShow.Show(getApplicationContext(), "开锁成功");
				// 改变开锁图标
				// 2秒后复原
				//更新一次开锁记录
				sendOpenStatus();
				// 上报一次状态
				uploadRecord();
				break;
			case 1:
				
				break;
			default:
				break;
			}
		}
	};
	
	private void checkTimeout(){
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(mSvProgressBar.isShowing()){
					mSvProgressBar.dismiss();
					ToastShow.Show(getApplicationContext(), "开锁失败");
				}
			}
		}, 8*1000);
	}

	private void sendOpenStatus() {
		Log.i("wmy", "改变状态");
		mLockb.setImageResource(R.drawable.suo12x);
		mLockb.setClickable(false);
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mLockb.setImageResource(R.drawable.suo22x);
				mLockb.setClickable(true);
				records.clear();
				getRecord(1);
			}
		}, 2000);
	}

	private void uploadRecord() {
		
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_lock;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mRecordL = $(R.id.record_lv);
		mLockb = $(R.id.lock_img);
		mRegisterB = $(R.id.register_btn);
		mCancelB = $(R.id.cancel_btn);
		mRecordL = $(R.id.record_lv);
		boolVersion();
		mBackL.setOnClickListener(this);
		mLockb.setOnClickListener(this);
		mRegisterB.setOnClickListener(this);
		mCancelB.setOnClickListener(this);
		p = getIntent().getIntExtra("position", 9999);
		device = DeviceManager.getInstance().getLocks().get(p);
		socket = SocketManager.getInstance().sMap.get(device.getMainDeviceId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "该门锁无绑定网关！无法被控制");
			finish();
		}else if(!socket.isLocalSuccess()){
			ToastShow.Show(getApplicationContext(), "远程连接的网关无法控制门锁");
			finish();
		}
		setRecall();
		initCmd();
		mAdapter = new LockRecordAdapter(getApplicationContext(), records);
		mRecordL.setAdapter(mAdapter);
		getRecord(1);
		mSvProgressBar = new SVProgressHUD(RemoteLockActivity.this);
	}

	private void setRecall() {
		// TODO Auto-generated method stub
		socket.setRecDataCallBackListener_Lock(new RecDataCallBackListener_Lock() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				Log.i("wmy", "控制门锁返回" + data);
				int macRecInt[] = parseData(data);
				Log.i("wmy", "获取数据" + " " + macRecInt[0] + " " + macRecInt[1]
						+ " " + macRecInt[2] + " " + macRecInt[3]);
				if (macRecInt[0] == 16 && macRecInt[1] == macInt[0]
						&& macRecInt[2] == macInt[1]
						&& macRecInt[3] == macInt[2]
						&& macRecInt[4] == macInt[3]) {
					String upload = getUploadCmd(data);
					SocketManager.getInstance().uploadLockRecord(upload);
					Message msg = Message.obtain();
					msg.what = 0;
					mHandler.sendMessage(msg);
				}
			}
		});
	}

	private int[] parseData(String data) {
		int macRecInt[] = new int[5];
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);
			JSONArray ja = jo1.getJSONArray("data");
			macRecInt[0] = ja.getInt(9);
			macRecInt[1] = ja.getInt(10);
			macRecInt[2] = ja.getInt(11);
			macRecInt[3] = ja.getInt(12);
			macRecInt[4] = ja.getInt(13);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return macRecInt;
	}

	private String getUploadCmd(String data) {
		String cmd = "";
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			cmd = ConvertUtil.getInstance().convertUploadCmd(
					device.getDeviceID(), g);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cmd;
	}

	private void initCmd() {
		String mac = device.getDeviceAddress().substring(0, 8);
		Log.i("wmy", "mac = " + mac);
		byte[] macByte = Util.hexStringToBytes(mac);
		macInt = Util.byte2HexStr(macByte);
		int[] getData = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8, 34, 0,
				0, 0, 0, 0, 1, 0 };
		int[] getData1 = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8, 35, 0,
				0, 0, 0, 0, 1, 0 };
		int[] getData2 = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8, 36, 0,
				0, 0, 0, 0, 1, 0 };
		getData[10] = macInt[0];
		getData[11] = macInt[1];
		getData[12] = macInt[2];
		getData[13] = macInt[3];
		int n = 0;
		for (int i = 7; i < 16; i++) {
			n += getData[i];
		}
		getData[16] = n % 256;

		getData1[10] = macInt[0];
		getData1[11] = macInt[1];
		getData1[12] = macInt[2];
		getData1[13] = macInt[3];
		n = 0;
		for (int i = 7; i < 16; i++) {
			n += getData1[i];
		}
		getData1[16] = n % 256;

		getData2[10] = macInt[0];
		getData2[11] = macInt[1];
		getData2[12] = macInt[2];
		getData2[13] = macInt[3];
		n = 0;
		for (int i = 7; i < 16; i++) {
			n += getData2[i];
		}
		getData2[16] = n % 256;
		registerCmd = ConvertUtil.convertGetLockCmd(getData);
		cancelCmd = ConvertUtil.convertGetLockCmd(getData1);
		openCmd = ConvertUtil.convertGetLockCmd(getData2);
	}

	private void initData(){
		mAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}
	
	private void getRecord(int page1){
		this.page = page1;
		RequestParams params = new RequestParams(HttpURL.GET_LOCK_RECORD);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("deviceId", device.getDeviceID());
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("page",page);
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						JSONObject jo = jsonObject.optJSONObject("data");
						if(jo==null){
							return;
						}
						JSONArray ja = jo.getJSONArray("list");
						for(int i = 0;i<ja.length();i++){
							JSONObject recordJo  = ja.getJSONObject(i);
							int logId = recordJo.getInt("logId");
							String deviceId = recordJo.getString("deviceId");
							String statusPackage = recordJo.getString("statusPackage");
							long createTime = recordJo.getLong("createTime");
							int status = recordJo.getInt("status");
							LockRecord lr = new LockRecord(logId, deviceId, statusPackage, status, createTime);
							records.add(lr);
						}
						boolean hasNextPage = jo.getBoolean("hasNextPage");
						if(hasNextPage){
							page++;
							getRecord(page);
						}else{
							//获取完毕
//							Message msg = Message.obtain();
							initData();
						}
						
					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "获取开锁记录失败："
								+ errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

}
